//
//  UserOfMessage.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 08/05/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit

class UserOfMessage: NSObject {

    var user:UserBaseModel?
    var direct_message:DirectMessage?
    
    
    
    class func loadMessageList(finished: @escaping(_ models:[UserOfMessage]?)->()) {
        
        let path =  Bundle.main.path(forResource:"MessageList", ofType: "json")
        let url = URL(fileURLWithPath: path!)
        do{
            let data = try Data(contentsOf: url)
            let json:Any = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)
            let dic = json as? [String:Any]
            // 2.遍历数组, 将字典转换为模型
           let list = dict2Model(list: dic!["user_list"] as? [[String: Any]])
            finished(list)
        }catch let erro as Error!{
            
            
        }

    }
    
    
    /// 将字典数组转换为模型数组
    class func dict2Model(list: [[String: Any]]?) -> [UserOfMessage]? {
        if ((list?.count) != nil) {
            var models = [UserOfMessage]()
            for dict in list!
            {
                models.append(UserOfMessage(dict: dict as! [String : AnyObject]))
            }
            return models
        }
        return nil
    }
    
    
    // 字典转模型
    init(dict: [String: Any])
    {
        super.init()
        setValuesForKeys(dict)
    }
    // setValuesForKeys(dict)方法会调用 setValue
    override func setValue(_ value: Any?, forKey key: String) {
        // 1.判断当前是否正在给微博字典中的user字典赋值
        if "user" == key
        {
            // 2.根据user key对应的字典创建一个模型
            user = UserBaseModel(dict: value as! [String : AnyObject])
            return
        }
        
        // 2.判断是否是转发微博, 如果是就自己处理
        if "direct_message" == key
        {
            direct_message = DirectMessage(dict: value as! [String : AnyObject])
            return
        }
        // 3,调用父类方法, 按照系统默认处理
        super.setValue(value, forKey: key)
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
   
}
